package cs551.listtracker;

/*
 * Copyright (C) 2013 Surviving with Android (http://www.survivingwithandroid.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import cs551.listtracker.ListFragment.ItemListener;
import cs551.listtracker.adapter.ListofListsAdapter;
import cs551.listtracker.structure.ListContainer;
import cs551.listtracker.structure.ShoppingList;

public class ListofListsFragment extends Fragment {

	// private List<Bookmark> bookmarkList = new
	// ArrayList<ListBookmarkFragment.Bookmark>();
	List<ShoppingList> shoppingListList;// = new ArrayList<ShoppingList>();
	ListofListsAdapter lla;

	SharedPreferences settings;

	// ListsDbAdapter dbHelper;
	int temp;
	int currentList = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		shoppingListList = ((MainActivity) getActivity()).shoppingListList;
		settings = ((MainActivity) getActivity()).settings;
	}

	@Override
	public void onAttach(Activity activity) {

		// It's time we check if our activity implements the right inteface
		if ((!(activity instanceof ListListener))
				|| (!(activity instanceof ItemListener)))
			throw new ClassCastException();

		super.onAttach(activity);
		// if (((MainActivity) getActivity()).prefs_usedb)
		// dbHelper = new ListsDbAdapter(activity);
		// if (((MainActivity) getActivity()).prefs_usedb)
		// dbHelper.open();
		//
		// ((MainActivity) getActivity()).dbHelper = dbHelper;
		// ((MainActivity) getActivity()).shoppingListList = shoppingListList;

		// ((MainActivity) getActivity()).onChangeList(shoppingListList.get(0),
		// 0);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.leftside_layout, container, true);
		ListView lView = (ListView) v.findViewById(R.id.listList);
		lla = new ListofListsAdapter(shoppingListList, getActivity());
		lView.setAdapter(lla);
		lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				currentList = position;
				System.out.println("Autohide: "
						+ settings.getBoolean("autodelete", false));
				((ListListener) getActivity()).onChangeList(shoppingListList
						.get(position));
				getActivity().getActionBar().setTitle(
						shoppingListList.get(position).title);

			}
		});
		registerForContextMenu(lView);

		setHasOptionsMenu(true);
		return v;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		this.getView().setBackgroundColor(0xFFDDE5F0);
		// super.onViewCreated(view, savedInstanceState);

	}

	@Override
	public void onStart() {
		super.onStart();
		((MainActivity) getActivity()).init();
	}

	// We want to create a context Menu when the user long click on an item
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;

		// We know that each row in the adapter is a Map
		ShoppingList shoppingList = shoppingListList.get(aInfo.position);

		menu.setHeaderTitle("Options for " + shoppingList.title);
		menu.add(1, 1, 1, "Delete");
		menu.add(1, 2, 2, "Rename");
		menu.add(1, 3, 3, "Duplicate");
		menu.add(1, 4, 4, "Export");

	}

	// This method is called when user selects an Item in the Context menu
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getGroupId() == 1) {
			System.out.println("Caught LoL Context menu: " + item.getGroupId()
					+ " " + item.getItemId());
			AdapterContextMenuInfo aInfo;
			switch (item.getItemId()) {
			case 1:
				aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
				shoppingListList.remove(aInfo.position);
				// if (((MainActivity) getActivity()).prefs_usedb)
				// dbHelper.deleteList((long) aInfo.position);
				lla.notifyDataSetChanged();
				break;
			case 2:// rename

				aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
				temp = aInfo.position;
				final Dialog d = new Dialog(getActivity());
				d.setContentView(R.layout.renamedialog);
				d.setTitle("Rename List");
				d.setCancelable(true);
				final AutoCompleteTextView edit = (AutoCompleteTextView) d
						.findViewById(R.id.list_EditText);
				edit.setText(shoppingListList.get(aInfo.position).title);
				edit.selectAll();
				Button b = (Button) d.findViewById(R.id.button1);

				b.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						String listName = edit.getText().toString();
						shoppingListList.get(temp).title = listName;
						// lla.clear();// //shouldnt fix the problem and can be
						// rmeovesd
						// lla.addAll(shoppingListList);// shouldnt fix the
						// problem
						// and can be rmeovesd

						if (temp == currentList)
							getActivity().getActionBar().setTitle(
									shoppingListList.get(currentList).title);

						lla.notifyDataSetChanged();

						d.dismiss();
					}
				});
				d.show();

				break;
			case 3:
				aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
					ShoppingList duplicateList = (shoppingListList
							.get(aInfo.position)).duplicate();

					shoppingListList.add(duplicateList);

					lla.notifyDataSetChanged();

				

				break;
			case 4:// Export
				aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
				String state = Environment.getExternalStorageState();
				if (Environment.MEDIA_MOUNTED.equals(state)) {
					File path = Environment.getExternalStorageDirectory();
					FileOutputStream fos;

					// for (ShoppingList explist : shoppingListList) {
					try {
						File file = new File(
								path.getAbsolutePath() + "/lists/",
								shoppingListList.get(aInfo.position).title
										+ ".xml");
						if (!file.getParentFile().exists())
							file.getParentFile().mkdir();
						fos = new FileOutputStream(file);

						shoppingListList.get(aInfo.position)
								.exportListToWriter(fos);
						Toast.makeText(getActivity(),
								"Exported: " + file.getName(),
								Toast.LENGTH_SHORT).show();
					} catch (Exception e) {
						e.printStackTrace();
					}
					// }
				}
			}
			return super.onContextItemSelected(item);
		}
		return false;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.left_menu, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle presses on the action bar items

		switch (item.getItemId()) {
		case R.id.action_addlist:

			final Dialog d = new Dialog(getActivity());
			d.setContentView(R.layout.listdialog);
			d.setTitle("Add List");
			d.setCancelable(true);

			final EditText edit = (EditText) d.findViewById(R.id.list_EditText);
			Button b = (Button) d.findViewById(R.id.button1);

			b.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					String listName = edit.getText().toString();
					ShoppingList shoppingList = new ShoppingList(listName);
					ListofListsFragment.this.shoppingListList.add(shoppingList);
					// try {
					// if (((MainActivity) getActivity()).prefs_usedb)
					// dbHelper.AddList(shoppingList);
					// } catch (IOException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// }
					lla.notifyDataSetChanged();

					// We notify the data model is changed
					d.dismiss();
				}
			});

			d.show();

			return true;
		case R.id.settings:
			fireSettings();
			break;

		}

		return super.onOptionsItemSelected(item);
	}

	public void fireSettings() {
		Intent intent = new Intent(getActivity(), SettingsActivity.class);
		intent.putExtra("lists", ((MainActivity) getActivity()).listContainer);
		startActivityForResult(intent, 1);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// A better structure for this would be:
		// Check resultCode >= 8
		// {
		// //Stuff
		// resultcode-=8
		// }
		// Check resultCode >= 4
		// {
		// //Stuff
		// resultcode-=4
		// }
		// Check resultCode >= 2
		// {
		// //Stuff
		// resultcode-=2
		// }
		// Check resultCode >= 1
		// {
		// //Stuff
		// resultcode-=1
		// }

		System.out.println("Got clear request: " + resultCode);
		Boolean update = false;
		if (resultCode != 0)
			update = true;

		if (resultCode >= 8) {
			ListContainer lc = (ListContainer) data.getParcelableExtra("lists");

			((MainActivity) getActivity()).listContainer = lc;
			((MainActivity) getActivity()).shoppingListList = lc.lists;

			System.out.println("received "
					+ ((ListContainer) data.getParcelableExtra("lists")).lists
							.size() + " lists!");
			((MainActivity) getActivity()).init();

			lla.clear();
			lla.addAll(lc.lists);

			resultCode -= 8;
		}
		if (resultCode >= 4) {
			((MainActivity) getActivity()).shoppingListList.clear();
			((MainActivity) getActivity()).populateTestData();

			resultCode -= 4;
		}
		if (resultCode >= 2) {
			((MainActivity) getActivity()).shoppingListList.clear();
			((MainActivity) getActivity()).init();

			resultCode -= 2;
		}
		if (resultCode >= 1) {

			((MainActivity) getActivity()).history.clear();

		}
		if (update) {
			lla.notifyDataSetChanged();
			// ((ListListener) getActivity()).onChangeList();
		}
		//
		// if (resultCode == 1)
		// ((MainActivity) getActivity()).history.clear();
		// else if (resultCode == 2) {
		// ((MainActivity) getActivity()).shoppingListList.clear();
		// ((MainActivity) getActivity()).init();
		// } else if (resultCode == 3) {
		// ((MainActivity) getActivity()).history.clear();
		// ((MainActivity) getActivity()).shoppingListList.clear();
		// ((MainActivity) getActivity()).init();
		//
		// } else if (resultCode == 4 || resultCode == 6) {
		// ((MainActivity) getActivity()).shoppingListList.clear();
		// ((MainActivity) getActivity()).populateTestData();
		// } else if (resultCode == 5 || resultCode == 7) {
		// ((MainActivity) getActivity()).history.clear();
		// ((MainActivity) getActivity()).shoppingListList.clear();
		// ((MainActivity) getActivity()).populateTestData();
		// }
		if (resultCode != 0) {
			lla.notifyDataSetChanged();
			// ((ListListener) getActivity()).onChangeList();
		}
	}

	public void updateLists() {
		System.out.println("Updating Lists");
		lla.notifyDataSetChanged();
	}

	public interface ListListener {
		public void onChangeList(ShoppingList shopList);

		public void onChangeList();
	}
}
